/**
  ******************************************************************************
  * @file    stm32f1xx_hal_gpio.c
  * @author  MCD Application Team
  * @brief   GPIO HAL module driver.
  *          This file provides firmware functions to manage the following
  *          functionalities of the General Purpose Input/Output (GPIO) peripheral:
  *           + Initialization and de-initialization functions
  *           + IO operation functions
  *
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2016 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  @verbatim
  ==============================================================================
                    ##### GPIO Peripheral features #####
  ==============================================================================
  [..]
  Subject to the specific hardware characteristics of each I/O port listed in the datasheet, each
  port bit of the General Purpose IO (GPIO) Ports, can be individually configured by software
  in several modes:
  (+) Input mode
  (+) Analog mode
  (+) Output mode
  (+) Alternate function mode
  (+) External interrupt/event lines

  [..]
  During and just after reset, the alternate functions and external interrupt
  lines are not active and the I/O ports are configured in input floating mode.

  [..]
  All GPIO pins have weak internal pull-up and pull-down resistors, which can be
  activated or not.

  [..]
  In Output or Alternate mode, each IO can be configured on open-drain or push-pull
  type and the IO speed can be selected depending on the VDD value.

  [..]
  All ports have external interrupt/event capability. To use external interrupt
  lines, the port must be configured in input mode. All available GPIO pins are
  connected to the 16 external interrupt/event lines from EXTI0 to EXTI15.

  [..]
  The external interrupt/event controller consists of up to 20 edge detectors in connectivity
  line devices, or 19 edge detectors in other devices for generating event/interrupt requests.
  Each input line can be independently configured to select the type (event or interrupt) and
  the corresponding trigger event (rising or falling or both). Each line can also masked
  independently. A pending register maintains the status line of the interrupt requests

                     ##### How to use this driver #####
  ==============================================================================
 [..]
   (#) Enable the GPIO APB2 clock using the following function : __HAL_RCC_GPIOx_CLK_ENABLE().

   (#) Configure the GPIO pin(s) using HAL_GPIO_Init().
       (++) Configure the IO mode using "Mode" member from GPIO_InitTypeDef structure
       (++) Activate Pull-up, Pull-down resistor using "Pull" member from GPIO_InitTypeDef
            structure.
       (++) In case of Output or alternate function mode selection: the speed is
            configured through "Speed" member from GPIO_InitTypeDef structure
       (++) Analog mode is required when a pin is to be used as ADC channel
            or DAC output.
       (++) In case of external interrupt/event selection the "Mode" member from
            GPIO_InitTypeDef structure select the type (interrupt or event) and
            the corresponding trigger event (rising or falling or both).

   (#) In case of external interrupt/event mode selection, configure NVIC IRQ priority
       mapped to the EXTI line using HAL_NVIC_SetPriority() and enable it using
       HAL_NVIC_EnableIRQ().

   (#) To get the level of a pin configured in input mode use HAL_GPIO_ReadPin().

   (#) To set/reset the level of a pin configured in output mode use
       HAL_GPIO_WritePin()/HAL_GPIO_TogglePin().

   (#) To lock pin configuration until next reset use HAL_GPIO_LockPin().

   (#) During and just after reset, the alternate functions are not
       active and the GPIO pins are configured in input floating mode (except JTAG
       pins).

   (#) The LSE oscillator pins OSC32_IN and OSC32_OUT can be used as general purpose
       (PC14 and PC15, respectively) when the LSE oscillator is off. The LSE has
       priority over the GPIO function.

   (#) The HSE oscillator pins OSC_IN/OSC_OUT can be used as
       general purpose PD0 and PD1, respectively, when the HSE oscillator is off.
       The HSE has priority over the GPIO function.

  @endverbatim
  ******************************************************************************
  */

// 包含 STM32F1xx HAL 库的头文件
#include "stm32f1xx_hal.h"

/** @addtogroup STM32F1xx_HAL_Driver
  * @{
  */

/** @defgroup GPIO GPIO
  * @brief GPIO HAL module driver
  * @{
  */

// 如果启用了 GPIO HAL 模块
#ifdef HAL_GPIO_MODULE_ENABLED

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @addtogroup GPIO_Private_Constants GPIO Private Constants
  * @{
  */
// 用于提取 GPIO 模式的掩码
#define GPIO_MODE             0x00000003u
// 用于指示外部中断/事件模式的标志
#define EXTI_MODE             0x10000000u
// 用于指示外部中断模式的标志
#define GPIO_MODE_IT          0x00010000u
// 用于指示外部事件模式的标志
#define GPIO_MODE_EVT         0x00020000u
// 用于指示上升沿触发的标志
#define RISING_EDGE           0x00100000u
// 用于指示下降沿触发的标志
#define FALLING_EDGE          0x00200000u
// 用于指示 GPIO 输出类型的掩码
#define GPIO_OUTPUT_TYPE      0x00000010u

// 每个 GPIO 端口的引脚数量
#define GPIO_NUMBER           16u

/* Definitions for bit manipulation of CRL and CRH register */
// 配置引脚为输入模式（复位状态）
#define  GPIO_CR_MODE_INPUT         0x00000000u /*!< 00: Input mode (reset state)  */
// 配置引脚为模拟模式
#define  GPIO_CR_CNF_ANALOG         0x00000000u /*!< 00: Analog mode  */
// 配置引脚为浮空输入模式（复位状态）
#define  GPIO_CR_CNF_INPUT_FLOATING 0x00000004u /*!< 01: Floating input (reset state)  */
// 配置引脚为上拉/下拉输入模式
#define  GPIO_CR_CNF_INPUT_PU_PD    0x00000008u /*!< 10: Input with pull-up / pull-down  */
// 配置引脚为通用推挽输出模式
#define  GPIO_CR_CNF_GP_OUTPUT_PP   0x00000000u /*!< 00: General purpose output push-pull  */
// 配置引脚为通用开漏输出模式
#define  GPIO_CR_CNF_GP_OUTPUT_OD   0x00000004u /*!< 01: General purpose output Open-drain  */
// 配置引脚为复用推挽输出模式
#define  GPIO_CR_CNF_AF_OUTPUT_PP   0x00000008u /*!< 10: Alternate function output Push-pull  */
// 配置引脚为复用开漏输出模式
#define  GPIO_CR_CNF_AF_OUTPUT_OD   0x0000000Cu /*!< 11: Alternate function output Open-drain  */

/**
  * @}
  */
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @defgroup GPIO_Exported_Functions GPIO Exported Functions
  * @{
  */

/** @defgroup GPIO_Exported_Functions_Group1 Initialization and de-initialization functions
 *  @brief    Initialization and Configuration functions
 *
@verbatim
 ===============================================================================
              ##### Initialization and de-initialization functions #####
 ===============================================================================
  [..]
    This section provides functions allowing to initialize and de-initialize the GPIOs
    to be ready for use.

@endverbatim
  * @{
  */


/**
  * @brief  Initializes the GPIOx peripheral according to the specified parameters in the GPIO_Init.
  * @param  GPIOx: where x can be (A..G depending on device used) to select the GPIO peripheral
  * @param  GPIO_Init: pointer to a GPIO_InitTypeDef structure that contains
  *         the configuration information for the specified GPIO peripheral.
  * @retval None
  */
void HAL_GPIO_Init(GPIO_TypeDef  *GPIOx, GPIO_InitTypeDef *GPIO_Init)
{
  // 用于循环遍历引脚的位置计数器
  uint32_t position = 0x00u;
  // 当前处理的引脚位置
  uint32_t ioposition;
  // 当前处理的引脚是否有效
  uint32_t iocurrent;
  // 临时变量，用于存储寄存器值
  uint32_t temp;
  // 用于存储要配置的寄存器值
  uint32_t config = 0x00u;
  // 指向 CRL 或 CRH 寄存器的指针
  __IO uint32_t *configregister; /* Store the address of CRL or CRH register based on pin number */
  // 用于计算 CNF 和 MODE 位在 CRL 或 CRH 寄存器中的偏移量
  uint32_t registeroffset;       /* offset used during computation of CNF and MODE bits placement inside CRL or CRH register */

  // 检查 GPIOx 参数是否有效
  assert_param(IS_GPIO_ALL_INSTANCE(GPIOx));
  // 检查 GPIO_Init->Pin 参数是否有效
  assert_param(IS_GPIO_PIN(GPIO_Init->Pin));
  // 检查 GPIO_Init->Mode 参数是否有效
  assert_param(IS_GPIO_MODE(GPIO_Init->Mode));

  // 遍历所有引脚
  while (((GPIO_Init->Pin) >> position) != 0x00u)
  {
    // 获取当前引脚的位置
    ioposition = (0x01uL << position);

    // 获取当前引脚是否有效
    iocurrent = (uint32_t)(GPIO_Init->Pin) & ioposition;

    if (iocurrent == ioposition)
    {
      // 检查 GPIOx 是否为有效的复用功能实例
      assert_param(IS_GPIO_AF_INSTANCE(GPIOx));

      // 根据所需的模式，填充 config 变量，包含 MODEy[1:0] 和 CNFy[3:2] 对应的位
      switch (GPIO_Init->Mode)
      {
        // 如果配置引脚为推挽输出模式
        case GPIO_MODE_OUTPUT_PP:
          // 检查 GPIO 速度参数是否有效
          assert_param(IS_GPIO_SPEED(GPIO_Init->Speed));
          // 计算配置值
          config = GPIO_Init->Speed + GPIO_CR_CNF_GP_OUTPUT_PP;
          break;

        // 如果配置引脚为开漏输出模式
        case GPIO_MODE_OUTPUT_OD:
          // 检查 GPIO 速度参数是否有效
          assert_param(IS_GPIO_SPEED(GPIO_Init->Speed));
          // 计算配置值
          config = GPIO_Init->Speed + GPIO_CR_CNF_GP_OUTPUT_OD;
          break;

        // 如果配置引脚为复用推挽输出模式
        case GPIO_MODE_AF_PP:
          // 检查 GPIO 速度参数是否有效
          assert_param(IS_GPIO_SPEED(GPIO_Init->Speed));
          // 计算配置值
          config = GPIO_Init->Speed + GPIO_CR_CNF_AF_OUTPUT_PP;
          break;

        // 如果配置引脚为复用开漏输出模式
        case GPIO_MODE_AF_OD:
          // 检查 GPIO 速度参数是否有效
          assert_param(IS_GPIO_SPEED(GPIO_Init->Speed));
          // 计算配置值
          config = GPIO_Init->Speed + GPIO_CR_CNF_AF_OUTPUT_OD;
          break;

        // 如果配置引脚为输入模式（也适用于事件和中断模式）
        case GPIO_MODE_INPUT:
        case GPIO_MODE_IT_RISING:
        case GPIO_MODE_IT_FALLING:
        case GPIO_MODE_IT_RISING_FALLING:
        case GPIO_MODE_EVT_RISING:
        case GPIO_MODE_EVT_FALLING:
        case GPIO_MODE_EVT_RISING_FALLING:
          // 检查 GPIO 上拉/下拉参数是否有效
          assert_param(IS_GPIO_PULL(GPIO_Init->Pull));
          if (GPIO_Init->Pull == GPIO_NOPULL)
          {
            // 无上下拉，配置为浮空输入
            config = GPIO_CR_MODE_INPUT + GPIO_CR_CNF_INPUT_FLOATING;
          }
          else if (GPIO_Init->Pull == GPIO_PULLUP)
          {
            // 上拉输入
            config = GPIO_CR_MODE_INPUT + GPIO_CR_CNF_INPUT_PU_PD;

            // 设置对应的 ODR 位
            GPIOx->BSRR = ioposition;
          }
          else /* GPIO_PULLDOWN */
          {
            // 下拉输入
            config = GPIO_CR_MODE_INPUT + GPIO_CR_CNF_INPUT_PU_PD;

            // 复位对应的 ODR 位
            GPIOx->BRR = ioposition;
          }
          break;

        // 如果配置引脚为模拟输入模式
        case GPIO_MODE_ANALOG:
          // 配置为模拟输入
          config = GPIO_CR_MODE_INPUT + GPIO_CR_CNF_ANALOG;
          break;

        // 参数已通过 assert_param 检查
        default:
          break;
      }

      // 检查当前位属于前 8 位还是后 8 位，以确定访问 CRL 还是 CRH 寄存器
      configregister = (iocurrent < GPIO_PIN_8) ? &GPIOx->CRL     : &GPIOx->CRH;
      // 计算 CNF 和 MODE 位在 CRL 或 CRH 寄存器中的偏移量
      registeroffset = (iocurrent < GPIO_PIN_8) ? (position << 2u) : ((position - 8u) << 2u);

      // 将引脚的新配置应用到寄存器
      MODIFY_REG((*configregister), ((GPIO_CRL_MODE0 | GPIO_CRL_CNF0) << registeroffset), (config << registeroffset));

      /*--------------------- EXTI Mode Configuration ------------------------*/
      // 如果配置为外部中断/事件模式
      if ((GPIO_Init->Mode & EXTI_MODE) == EXTI_MODE)
      {
        // 使能 AFIO 时钟
        __HAL_RCC_AFIO_CLK_ENABLE();
        // 读取 EXTI 配置寄存器
        temp = AFIO->EXTICR[position >> 2u];
        // 清除对应位
        CLEAR_BIT(temp, (0x0Fu) << (4u * (position & 0x03u)));
        // 设置对应位
        SET_BIT(temp, (GPIO_GET_INDEX(GPIOx)) << (4u * (position & 0x03u)));
        // 将修改后的值写回 EXTI 配置寄存器
        AFIO->EXTICR[position >> 2u] = temp;

        // 启用或禁用上升沿触发
        if ((GPIO_Init->Mode & RISING_EDGE) == RISING_EDGE)
        {
          // 启用上升沿触发
          SET_BIT(EXTI->RTSR, iocurrent);
        }
        else
        {
          // 禁用上升沿触发
          CLEAR_BIT(EXTI->RTSR, iocurrent);
        }

        // 启用或禁用下降沿触发
        if ((GPIO_Init->Mode & FALLING_EDGE) == FALLING_EDGE)
        {
          // 启用下降沿触发
          SET_BIT(EXTI->FTSR, iocurrent);
        }
        else
        {
          // 禁用下降沿触发
          CLEAR_BIT(EXTI->FTSR, iocurrent);
        }

        // 配置事件掩码
        if ((GPIO_Init->Mode & GPIO_MODE_EVT) == GPIO_MODE_EVT)
        {
          // 启用事件掩码
          SET_BIT(EXTI->EMR, iocurrent);
        }
        else
        {
          // 禁用事件掩码
          CLEAR_BIT(EXTI->EMR, iocurrent);
        }

        // 配置中断掩码
        if ((GPIO_Init->Mode & GPIO_MODE_IT) == GPIO_MODE_IT)
        {
          // 启用中断掩码
          SET_BIT(EXTI->IMR, iocurrent);
        }
        else
        {
          // 禁用中断掩码
          CLEAR_BIT(EXTI->IMR, iocurrent);
        }
      }
    }

    // 移动到下一个引脚
    position++;
  }
}

/**
  * @brief  De-initializes the GPIOx peripheral registers to their default reset values.
  * @param  GPIOx: where x can be (A..G depending on device used) to select the GPIO peripheral
  * @param  GPIO_Pin: specifies the port bit to be written.
  *         This parameter can be one of GPIO_PIN_x where x can be (0..15).
  * @retval None
  */
void HAL_GPIO_DeInit(GPIO_TypeDef  *GPIOx, uint32_t GPIO_Pin)
{
  // 用于循环遍历引脚的位置计数器
  uint32_t position = 0x00u;
  // 当前处理的引脚是否有效
  uint32_t iocurrent;
  // 临时变量，用于存储寄存器值
  uint32_t tmp;
  // 指向 CRL 或 CRH 寄存器的指针
  __IO uint32_t *configregister; /* Store the address of CRL or CRH register based on pin number */
  // 用于计算 CNF 和 MODE 位在 CRL 或 CRH 寄存器中的偏移量
  uint32_t registeroffset;

  // 检查 GPIOx 参数是否有效
  assert_param(IS_GPIO_ALL_INSTANCE(GPIOx));
  // 检查 GPIO_Pin 参数是否有效
  assert_param(IS_GPIO_PIN(GPIO_Pin));

  // 遍历所有引脚
  while ((GPIO_Pin >> position) != 0u)
  {
    // 获取当前引脚是否有效
    iocurrent = (GPIO_Pin) & (1uL << position);

    if (iocurrent)
    {
      /*------------------------- EXTI Mode Configuration --------------------*/
      // 清除当前 IO 的外部中断或事件配置
      tmp = AFIO->EXTICR[position >> 2u];
      tmp &= 0x0FuL << (4u * (position & 0x03u));
      if (tmp == (GPIO_GET_INDEX(GPIOx) << (4u * (position & 0x03u))))
      {
        // 清除 EXTI 线配置
        CLEAR_BIT(EXTI->IMR, (uint32_t)iocurrent);
        CLEAR_BIT(EXTI->EMR, (uint32_t)iocurrent);

        // 清除上升沿和下降沿配置
        CLEAR_BIT(EXTI->FTSR, (uint32_t)iocurrent);
        CLEAR_BIT(EXTI->RTSR, (uint32_t)iocurrent);
        
        tmp = 0x0FuL << (4u * (position & 0x03u));
        CLEAR_BIT(AFIO->EXTICR[position >> 2u], tmp);
      }
      /*------------------------- GPIO Mode Configuration --------------------*/
      // 检查当前位属于前 8 位还是后 8 位，以确定访问 CRL 还是 CRH 寄存器
      configregister = (iocurrent < GPIO_PIN_8) ? &GPIOx->CRL     : &GPIOx->CRH;
      // 计算 CNF 和 MODE 位在 CRL 或 CRH 寄存器中的偏移量
      registeroffset = (iocurrent < GPIO_PIN_8) ? (position << 2u) : ((position - 8u) << 2u);

      // CRL/CRH 默认值为浮空输入(0x04) 并移动到正确位置
      MODIFY_REG(*configregister, ((GPIO_CRL_MODE0 | GPIO_CRL_CNF0) << registeroffset), GPIO_CRL_CNF0_0 << registeroffset);

      // ODR 默认值为 0
      CLEAR_BIT(GPIOx->ODR, iocurrent);
    }

    // 移动到下一个引脚
    position++;
  }
}

/**
  * @}
  */

/** @defgroup GPIO_Exported_Functions_Group2 IO operation functions
 *  @brief   GPIO Read and Write
 *
@verbatim
 ===============================================================================
                       ##### IO operation functions #####
 ===============================================================================
  [..]
    This subsection provides a set of functions allowing to manage the GPIOs.

@endverbatim
  * @{
  */

/**
  * @brief  Reads the specified input port pin.
  * @param  GPIOx: where x can be (A..G depending on device used) to select the GPIO peripheral
  * @param  GPIO_Pin: specifies the port bit to read.
  *         This parameter can be GPIO_PIN_x where x can be (0..15).
  * @retval The input port pin value.
  */
GPIO_PinState HAL_GPIO_ReadPin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin)
{
  // 用于存储引脚状态的变量
  GPIO_PinState bitstatus;

  // 检查 GPIO_Pin 参数是否有效
  assert_param(IS_GPIO_PIN(GPIO_Pin));

  // 读取输入数据寄存器并判断引脚状态
  if ((GPIOx->IDR & GPIO_Pin) != (uint32_t)GPIO_PIN_RESET)
  {
    bitstatus = GPIO_PIN_SET;
  }
  else
  {
    bitstatus = GPIO_PIN_RESET;
  }
  return bitstatus;
}

/**
  * @brief  Sets or clears the selected data port bit.
  *
  * @note   This function uses GPIOx_BSRR register to allow atomic read/modify
  *         accesses. In this way, there is no risk of an IRQ occurring between
  *         the read and the modify access.
  *
  * @param  GPIOx: where x can be (A..G depending on device used) to select the GPIO peripheral
  * @param  GPIO_Pin: specifies the port bit to be written.
  *          This parameter can be one of GPIO_PIN_x where x can be (0..15).
  * @param  PinState: specifies the value to be written to the selected bit.
  *          This parameter can be one of the GPIO_PinState enum values:
  *            @arg GPIO_PIN_RESET: to clear the port pin
  *            @arg GPIO_PIN_SET: to set the port pin
  * @retval None
  */
void HAL_GPIO_WritePin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin, GPIO_PinState PinState)
{
  // 检查 GPIO_Pin 参数是否有效
  assert_param(IS_GPIO_PIN(GPIO_Pin));
  // 检查 PinState 参数是否有效
  assert_param(IS_GPIO_PIN_ACTION(PinState));

  if (PinState != GPIO_PIN_RESET)
  {
    // 设置引脚
    GPIOx->BSRR = GPIO_Pin;
  }
  else
  {
    // 清除引脚
    GPIOx->BSRR = (uint32_t)GPIO_Pin << 16u;
  }
}

/**
  * @brief  Toggles the specified GPIO pin
  * @param  GPIOx: where x can be (A..G depending on device used) to select the GPIO peripheral
  * @param  GPIO_Pin: Specifies the pins to be toggled.
  * @retval None
  */
void HAL_GPIO_TogglePin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin)
{
  // 用于存储当前输出数据寄存器的值
  uint32_t odr;

  // 检查 GPIO_Pin 参数是否有效
  assert_param(IS_GPIO_PIN(GPIO_Pin));

  // 获取当前输出数据寄存器的值
  odr = GPIOx->ODR;

  // 设置低电平的引脚，复位高电平的引脚
  GPIOx->BSRR = ((odr & GPIO_Pin) << GPIO_NUMBER) | (~odr & GPIO_Pin);
}

/**
* @brief  Locks GPIO Pins configuration registers.
* @note   The locking mechanism allows the IO configuration to be frozen. When the LOCK sequence
*         has been applied on a port bit, it is no longer possible to modify the value of the port bit until
*         the next reset.
* @param  GPIOx: where x can be (A..G depending on device used) to select the GPIO peripheral
* @param  GPIO_Pin: specifies the port bit to be locked.
*         This parameter can be any combination of GPIO_Pin_x where x can be (0..15).
* @retval None
*/
HAL_StatusTypeDef HAL_GPIO_LockPin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin)
{
  // 用于存储锁存寄存器的值
  __IO uint32_t tmp = GPIO_LCKR_LCKK;

  // 检查 GPIOx 参数是否有效
  assert_param(IS_GPIO_LOCK_INSTANCE(GPIOx));
  // 检查 GPIO_Pin 参数是否有效
  assert_param(IS_GPIO_PIN(GPIO_Pin));

  // 应用锁键写入序列
  SET_BIT(tmp, GPIO_Pin);
  // 设置 LCKx 位: LCKK='1' + LCK[15-0]
  GPIOx->LCKR = tmp;
  // 复位 LCKx 位: LCKK='0' + LCK[15-0]
  GPIOx->LCKR = GPIO_Pin;
...